#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
      int val;
     TreeNode *left;
        TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };
 
class Solution {
public:
    bool Find(TreeNode* root,TreeNode* x)
    {
        if(root==NULL)
            return false;
        return root==x||
        Find(root->right,x)||
        Find(root->left,x);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root ==  NULL)
            return nullptr;
        if(root == p || root == q)
            return root;
        
        bool PInLeft,PInRight,qInLeft,qInRight;

        PInLeft = Find(root->left,p);
        PInRight = !PInLeft;

        qInLeft = Find(root->left,q);
        qInRight = !qInLeft;

        if((qInLeft&&PInRight)||(qInRight&&PInLeft))
            return root;

        if(qInRight&&PInRight)
            return lowestCommonAncestor(root->right,p,q);
        if(qInLeft&&PInLeft)
            return lowestCommonAncestor(root->left,p,q);
        
        return NULL;

    }
};